<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | create by allen.qiang
// +----------------------------------------------------------------------

/**
 * 投票ajax类
 * @package  ajax
 * @subpackage  backend
 * @author   create by allen.qiang
 */

quanli_require('module/base/content/goodsComment.class.php');
quanli_require('module/base/goods/quanliGoods.class.php');
quanli_require('module/base/customer/quanliCust.class.php');
class ajax_comment {
	//入口
	public function execute(){
		$operFlg = isset($_REQUEST['operFlg']) ? $_REQUEST['operFlg'] : null;
		switch ($operFlg){
			case 1:
				$this->showCommentList();
				break;
			case 2://单条回复
			case 3://批量回复
				$this->editComment();
				break;
			case 4:
				$this->delete();
				break;
 			case 5: //新增评价检查商品是否存在
 				$this->checkGoods();
 				break;
            case 6: //查询新增评论用户是否已经是会员
                $this->checkUser();
                break;
            case 7: //保存评论相关信息
                $this->saveComment();
                break;
		}
	}

	private function showCommentList () {
		global $G_PGLOB;
		
		//当前页
		$page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 1;
		
		//每页显示条数
		$rp = isset($_REQUEST['rp']) ? $_REQUEST['rp'] : 10;
		
		//排序的列的名称
		$sortname = isset($_REQUEST['sortname']) ? $_REQUEST['sortname'] : 'bill_no';
		
		//排序方式（正序、倒序）
		$sortorder = isset($_REQUEST['sortorder']) ? $_REQUEST['sortorder'] : 'DESC';
		
		$importData = array(
			'page' => $page,
			'rp'  => $rp,
			'sortname' => $sortname,
			'sortorder' => $sortorder,
            'comment_status' =>  isset($_REQUEST['comment_status']) ? $_REQUEST['comment_status'] : ''
		);
		
		//实例化内容公共类
		$goodsComment = new goodsComment($G_PGLOB->DBCA);
		
		$result_search = $goodsComment->searchComments($importData);
		
		//页面输出数组
		$result_array = array(
				'page' => $importData['page'],
				'total' => empty($result_search) ? 0 : $importData['count'],
				'rows' => array()
		);
		
		if ($result_search){
			
			$i = 0;
			
			foreach ($result_search as $commentList){

				if($commentList['comment_status'] == 0){
					$commentStatus = '未回复';
				}elseif ($commentList['comment_status'] == 1){
					$commentStatus = '已回复';
				}

				if( $commentList['comment_from'] == 0 ){
                    $comment_from_name = '前台';
                }else{
                    $comment_from_name = '后台';
                }
				$result_array['rows'][] = array(
						'id' => $commentList['comment_id'],
						'cell' => array(
								'<a href="javascript:void(0);" onclick="source.answer(\''.$commentList['comment_id'].'\');">回复</a>',
								'<a target="_blank" href="'.$commentList['link'].'">'.$commentList['goodsName'].'</a>',
                                $commentList['comment_content'],
                                $commentList['createTime'],
                                $comment_from_name,
                                $commentList['creator'],
                                $commentList['answer_dateTime'],
                                $commentList['answer_userID'],
                                $commentStatus
						)
				);
				$i++;
			}
		}
		
		echo json_encode($result_array);
	}
	
	//回复，operFlg：2单条，3批量
	private function editComment(){

		global $G_PGLOB;
		
		$operFlg = isset($_REQUEST['operFlg']) ? $_REQUEST['operFlg'] : null;
		$answerInfo = isset($_REQUEST['answer_content']) ? $_REQUEST['answer_content'] : null;
		$uuid = isset($_REQUEST['comment_id']) ? $_REQUEST['comment_id'] : null;
		$display = isset($_REQUEST['display']) ? $_REQUEST['display'] : null;
		$recommendFlg = isset($_REQUEST['recommend']) ? $_REQUEST['recommend'] : null;
        $satisfaction= isset($_REQUEST['satisfaction']) ? $_REQUEST['satisfaction'] : null;
		$uuidArr = isset($_REQUEST['uuidArr']) ? $_REQUEST['uuidArr'] : null;
		
		$importData = array('answer_content'   => $answerInfo,
							'comment_id'         => $uuid,
							'display'   => $display,
							'recommend' => $recommendFlg,
                            'satisfaction' => $satisfaction,
							'uuidArr'      => $uuidArr,
							'operFlg'	   => $operFlg,
							'answer_userID' => $G_PGLOB->currentUserID);
		
		//实例化内容公共类
		$goodsComment = new goodsComment($G_PGLOB->DBCA);
		
		$result_comment = $goodsComment->editComment($importData);
		
		echo json_encode($result_comment);
	}

	private function delete(){
		global $G_PGLOB;
		
		$uuidArr = isset($_REQUEST['uuidArr']) ? $_REQUEST['uuidArr'] : null;
		
		$importData = array('uuidArr' => $uuidArr);
		
		//实例化内容公共类
        $goodsComment = new goodsComment($G_PGLOB->DBCA);
		
		$result_del = $goodsComment->deleteComment($importData);
		
		echo json_encode($result_del);
	}

    /*
     *
     * 新增评价检查商品是否存在
     */
    public function checkGoods(){
        global $G_PGLOB;

        if( !isset( $_REQUEST['cityID'],$_REQUEST['goodsName'] ) || empty( $_REQUEST['cityID'] ) || empty( $_REQUEST['goodsName'] ) ){
            returnJsonData('参数错误');
        }

        //实例化商品类
        $quanliGoods = new quanliGoods( $G_PGLOB->DBCA );

        $arg_array = array(
            'cityID' => $_REQUEST['cityID'],
            'extend' => ' AND goodsName = "' .$_REQUEST['goodsName'].'"'
        );

        $goods_list_array = $quanliGoods->searchList( $arg_array );

        if( !$goods_list_array ){
            returnJsonData('该商品不存在',404);
        }

        $return_array = array(
            'twoPostID'=>$goods_list_array[0]['postID']
        );

        returnJsonData('ok',200,$return_array);

    }

    /*
     *
     * 检查新增评论用户是否已经是会员
     */
    public function checkUser(){
        global $G_PGLOB;

        if( !isset( $_REQUEST['userName']) || empty( $_REQUEST['userName'] ) ){
            returnJsonData( '参数错误' );
        }

        $arg_array = array(
            'custID' => $_REQUEST['userName']
        );


        $quanliCust = new ebsigCust( $G_PGLOB->DBCA );
        $cust_master = $quanliCust->getCustomerInfo( $arg_array );

        if( $cust_master ){
            returnJsonData( '当前手机号已是注册会员',200);
        }else{
            returnJsonData( '当前手机号尚未注册会员',404);
        }
    }


    //保存评论相关信息
    public function saveComment(){

        global $G_PGLOB;

        if (!isset($_REQUEST['goodsName'], $_REQUEST['twoPostID'], $_REQUEST['creator'], $_REQUEST['comment_item'], $_REQUEST['comment_content'])
            || empty($_REQUEST['goodsName']) || empty($_REQUEST['twoPostID']) || empty($_REQUEST['creator']) || !is_array($_REQUEST['comment_item']) || empty($_REQUEST['comment_content'])) {
            returnJsonData( '参数错误',404 );
        }

        //实例化商品类
        $quanliGoods = new quanliGoods( $G_PGLOB->DBCA );

        $arg_array = array(
            'cityID' => $_REQUEST['cityID'],
            'extend' => ' AND goodsName = "' .$_REQUEST['goodsName'].'"'
        );

        $goods_list_array = $quanliGoods->searchList( $arg_array );

        if( !$goods_list_array ){
            returnJsonData('该商品不存在',404);
        }

        $args_array = array(
            'custID' => $_REQUEST['creator']
        );

        $quanliCust = new ebsigCust( $G_PGLOB->DBCA );
        $cust_master = $quanliCust->getCustomerInfo( $args_array );

        if( $cust_master ){
            returnJsonData( '当前手机号已是注册会员',400);
        }

        try {

            $G_PGLOB->DBCA->beginTransaction();

                //保存订单评论信息
                $content_comments_obj = new entity('content_comments');
                $content_comments_obj->creator = $_REQUEST['creator'];
                $content_comments_obj->pcustID = '';
                $content_comments_obj->bill_no = '';
                $content_comments_obj->comment_content = $_REQUEST['comment_content'];
                $content_comments_obj->postID = '';
                $content_comments_obj->goodsName = $_REQUEST['goodsName'];
                $content_comments_obj->twoPostID = $_REQUEST['twoPostID'];
                $content_comments_obj->comment_from = 1;//后台添加
                $content_comments_obj->ip = get_ip();
                $G_PGLOB->DBCA->save($content_comments_obj);

                $comment_id = $G_PGLOB->DBCA->insert_id;

                //保存评论项
                foreach($_REQUEST['comment_item'] as &$item) {

                    if (!in_array($item, array(1, 2, 3, 4, 5))) {
                        throw new Exception('订单商品评价错误', 404);
                    }
                    $content_comments_item_obj = new entity('content_comments_item');
                    $content_comments_item_obj->creator = $_REQUEST['creator'];
                    $content_comments_item_obj->comment_id = $comment_id;
                    $content_comments_item_obj->comment_item = $item;
                    $content_comments_item_obj->comment_level = 5;
                    $G_PGLOB->DBCA->save($content_comments_item_obj);
                }

            $G_PGLOB->DBCA->commit();

            //删除商品评论数据缓存 add by allen.qiang 2015-05-28 Start

            $twoPostID = $_REQUEST['twoPostID'];
            $comment_item = $_REQUEST['comment_item'];

            $redis = &$G_PGLOB->memoryCache_Instance;

            //删除默认列表数据缓存
            $redis->remove('goods_comment_'.$twoPostID.'_0');

            //删除评论项列表数据缓存
            if(count($comment_item)>0){
                foreach($comment_item as $item){
                    $key = 'goods_comment_'.$twoPostID.'_'.$item;
                    $redis->remove($key);
                }
            }

            //删除商品评论数据缓存 add by allen.qiang 2015-05-28 End

            returnJsonData('商品评价提交成功',200);

        } catch (Exception $e) {

            $G_PGLOB->DBCA->rollBack();

            if ($e->getCode() > 0){
                return array('code'=> $e->getCode(), 'message'=> $e->getMessage());
            }else {
                error_log($e->getMessage());
                returnJsonData( '系统错误',500);
            }
        }
    }
}